import React from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, Spin, Collapse } from 'antd';
import { urlParse } from '@/utils/utils';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Basic from './addinfo/basic';
import Invoice from './addinfo/invoice';
import MailingAddress from './addinfo/mailingaddress';
import Bank from './addinfo/bank';
import Contacts from './addinfo/contact';

const { Panel } = Collapse;
const getInvoiceArrayData = data => {
  const indexList = [];
  Object.keys(data).forEach(key => {
    if (Object.prototype.hasOwnProperty.call(data, key) && key.indexOf('list_') > -1) {
      const index = Number(key.charAt(key.length - 1));
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  });
  return indexList.map(i => ({
    vatCoprName: data[`vatCoprName_list_${i}`],
    invType: data[`taxerType_list_${i}`].key,
    taxerIdNo: data[`taxerIdNo_list_${i}`],
    openBank: data[`openBank_list_${i}`] || '',
    bankAcco: data[`bankAcco_list_${i}`] || '',
    invPhone: data[`invPhone_list_${i}`] || '',
    invArea: data[`invArea_list_${i}`] || '',
    remark: data[`remark_list_${i}`] || '',
  }));
};

const getAddressArrayData = data => {
  const indexList = [];
  Object.keys(data).forEach(key => {
    if (Object.prototype.hasOwnProperty.call(data, key) && key.indexOf('list_') > -1) {
      const index = Number(key.charAt(key.length - 1));
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  });

  return indexList.map(i => ({
    contPerName: data[`contPerName_list_${i}`],
    contPerPhone: data[`contPerPhone_list_${i}`],
    mailArea: data[`mailAreaName_list_${i}`],
    mailCounty: data[`mailArea_list_${i}`][data[`mailArea_list_${i}`].length - 1],
    mailAddr: data[`mailAddr_list_${i}`],
    remark: data[`remark_list_${i}`] || '',
  }));
};

const getContactsArrayData = data => {
  const indexList = [];
  Object.keys(data).forEach(key => {
    if (Object.prototype.hasOwnProperty.call(data, key) && key.indexOf('list_') > -1) {
      const index = Number(key.charAt(key.length - 1));
      if (indexList.indexOf(index) === -1) {
        indexList.push(index);
      }
    }
  });

  return indexList.map(i => ({
    name: data[`name_list_${i}`],
    position: data[`position_list_${i}`],
    phoneNo: data[`phoneNo_list_${i}`],
    tel: data[`tel_list_${i}`] || '',
    email: data[`email_list_${i}`] || '',
    remark: data[`remark_list_${i}`] || '',
  }));
};
@connect(({ suppliermaintenance, loading }) => ({
  loading: loading.models.suppliermaintenance,
  activeKey: suppliermaintenance.activeKey,
  pageData: suppliermaintenance.pageData,
  formFieldsValue: suppliermaintenance.formFieldsValue,
  expandForm: suppliermaintenance.expandForm,
}))
@Form.create()
// 组合新增的数据：发票，地址，联系人,成本中心
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      dictList: ['SUPP_TYPE', 'TAXPAYER_TYPE', 'BANK_ID', 'MINI_INV_TYPE'],
      suppTypeList: [],
      taxerTypeList: [],
      activeKeyList: [],
      activeKey: '1',
      isHasSuppType: false,
    };
  }

  componentDidMount() {
    const { location, dispatch } = this.props;
    const { dictList, activeKey } = this.state;
    const active = urlParse(location.search).activeKey
      ? urlParse(location.search).activeKey
      : activeKey;
    this.setState({ activeKey: active, isHasSuppType: Number(active) === 1 });
    // 获取页面所需字典
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: dictList,
    }).then(data => {
      if (data.SUPP_TYPE) {
        const suppTypeList = [];
        data.SUPP_TYPE.forEach(item => {
          if (item.itemCode !== '1' && item.itemCode !== '4') {
            suppTypeList.push(item);
          }
        });
        this.setState({
          loading: false,
          suppTypeList,
          taxerTypeList: data.MINI_INV_TYPE,
          bankList: data.BANK_ID,
        });
      }
    });
  }

  getCustName = name => {
    this.setState({ custNames: name });
  };

  getCustNametwo = () => {};

  // 切换折叠面板
  changePanel = key => {
    this.setState({ activeKeyList: key });
  };

  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'suppliermaintenance/updateModelData',
      payload: {
        pageData: {
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
        formFieldsValue: {},
        expandForm: false,
        activeKey: '2',
      },
    });
    router.push(`/supplymanage/protection/index?activeKey=2`);
  };

  // 提交数据
  sumSubmit = e => {
    e.preventDefault();
    const { activeKeyList, activeKey, custNames } = this.state;
    const { dispatch } = this.props;
    let suppInfo = {};
    let isSubmit = true;
    let submitData = {};
    let suppInvoiceList = []; // 发票信息
    let suppMailAddrList = []; // 邮寄地址
    const suppBankAccountList = []; // 银行账户信息
    let suppContactList = []; // 联系人信息

    activeKeyList.forEach(key => {
      this[key].validateFieldsAndScroll((err, values) => {
        if (!err) {
          const obj = {};
          switch (key) {
            case 'invoiceInfo':
              suppInvoiceList = getInvoiceArrayData(values);
              break;
            case 'mailingAddressInfo':
              suppMailAddrList = getAddressArrayData(values);
              break;
            case 'bankInfo':
              Object.keys(values).forEach(keys => {
                if (values[keys] && values[keys].key) {
                  obj[keys] = values[keys].key;
                } else {
                  obj[keys] = values[keys] ? values[keys] : '';
                }
              });
              suppBankAccountList.push(obj);
              break;
            case 'contactsInfo':
              suppContactList = getContactsArrayData(values);
              break;
            default:
              break;
          }
        } else {
          isSubmit = false;
        }
      });
    });
    this.basicInfo.validateFieldsAndScroll((err, values) => {
      if (!err) {
        suppInfo = values;
        Object.keys(values).forEach(key => {
          if (values[key] && values[key].key) {
            suppInfo[key] = values[key].key;
          } else {
            suppInfo[key] = values[key] ? values[key] : '';
          }
        });
        suppInfo.name = custNames;
        submitData = {
          ...suppInfo,
          suppInvoiceList,
          suppMailAddrList,
          suppBankAccountList,
          suppContactList,
        };
      } else {
        isSubmit = false;
      }
    });
    if (isSubmit) {
      this.setState({ loading: true });
      const tempType =
        Number(activeKey) === 1 ? 'suppliermaintenance/insertPla' : 'suppliermaintenance/insert';
      dispatch({
        type: tempType,
        payload: submitData,
        callback: res => {
          this.setState({ loading: false });
          if (res.success) {
            message.success('新增成功', 2, () => {
              dispatch({
                type: 'suppliermaintenance/updateModelData',
                payload: {
                  pageData: {
                    pagination: {
                      current: 1,
                      pageSize: 10,
                      total: 10,
                    },
                  },
                  formFieldsValue: {},
                  expandForm: false,
                  activeKey: '2',
                },
              });
              router.push(`/supplymanage/protection/index?activeKey=${activeKey}`);
            });
          } else {
            message.warning(`${res.message || '新增失败！'}`);
          }
        },
      });
    }
  };

  render() {
    const {
      isHasSuppType,
      suppTypeList,
      taxerTypeList,
      bankList,
      loading,
      activeKeyList,
    } = this.state;
    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Basic
            ref={ref => {
              this.basicInfo = ref;
            }}
            isHasSuppType={isHasSuppType}
            suppTypeList={suppTypeList}
            getCustName={name => this.getCustName(name)}
            getCustNametwo={uniCreditCode => this.getCustNametwo(uniCreditCode)}
          />
          <Collapse
            style={{ marginBottom: 24 }}
            activeKey={activeKeyList}
            onChange={this.changePanel}
          >
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>发票信息</span>}
              key="invoiceInfo"
            >
              <Invoice
                taxerTypeList={taxerTypeList}
                ref={ref => {
                  this.invoiceInfo = ref;
                }}
              />
            </Panel>
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>邮寄地址信息</span>}
              key="mailingAddressInfo"
            >
              <MailingAddress
                ref={ref => {
                  this.mailingAddressInfo = ref;
                }}
              />
            </Panel>
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>银行账户信息</span>}
              key="bankInfo"
            >
              <Bank
                bankList={bankList}
                ref={ref => {
                  this.bankInfo = ref;
                }}
              />
            </Panel>
            <Panel
              header={<span style={{ fontWeight: 'bolder', fontSize: 16 }}>联系人信息</span>}
              key="contactsInfo"
            >
              <Contacts
                ref={ref => {
                  this.contactsInfo = ref;
                }}
              />
            </Panel>
          </Collapse>
          <FooterToolbar style={{ width: '100%' }}>
            <Button onClick={this.cancel} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button type="primary" onClick={this.sumSubmit}>
              提交
            </Button>
          </FooterToolbar>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default BasicForm;
